/* Copyright 2008 Shawn C. Dodd

This file is part of TagFC.  TagFC is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

TagFC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with TagFC.  If not, see <http://www.gnu.org/licenses/>. */

class WorksetController {
	def scaffold = Workset

	def workService					// injected
	def accountService

	def work = {
		def nick = session.nickname ?: "Anonymous"
		params.unpaidPieces = accountService.summarizeUnpaid( nick )

		// TODO  should I be using a command object instead of this ugly state machine?
		if( request.get ) {
			if( params.id ) {
				// view only
				// TODO  display lovely error page if workset doesn't exist
				return [ pieceList: Workset.get(params.id)?.included ]
			} else {
				// start of flow: lease and view
				def set = workService.leaseNewWorkset(nick)
				params.id = set.id
				redirect( uri:"/v1/work/set/${params.id}" )
			}
		} else if( request.post ) {
			if( params.id ) {
				// middle of flow: retire and lease and view
				def oldset = Workset.get(params.id)
				// TODO  panic if workset doesn't exist
				if( !params.containsKey('updateChoices') ) log.error "Oops! Bad form POST"
				def checked = params.findAll(checkedBoxes)
				checked = checked.collect(justId)
				HashSet ch = new HashSet(checked)
				workService.retireWorkset(oldset, ch)
				def newset = workService.leaseNewWorkset(nick,oldset)
				params.id = newset.id	
				redirect( uri:"/v1/work/set/${params.id}" )
			} else {
				// TODO  this shouldn't happen
				log.error "Bad state in WorksetController: post but no id"
			}
		} else {
			// WTF?
			log.error "Bizarro HTTP verb in request."
		}
	}

	def listCompleted = {
		if( !params.max ) params.max = 100
		if( !params.offset ) params.offset = 0
		if( !params.displayName ) params.displayName = "Anonymous"
		def nick = Nickname.findByDisplayName(params.displayName)
		//def sl = Workset.findAllByNickname(nick, [sort:"lastUpdated",order:"desc",max:params.max,offset:params.offset])

		[ setListCount:Workset.countByNickname(nick), setList:Workset.findAllByNickname(nick, [sort:"lastUpdated",order:"desc",max:params.max,offset:params.offset]) ]
	}

	def checkedBoxes = {
		it =~ /=on$/
	}

	def justId = {
		(it =~ /^cb(\d+)=on$/)[0][1]
	}

//   index = { }
}
